#!/usr/bin/python
# pip install esdk-obs-python --trusted-host pypi.org

import urllib.parse
from .base import BaseStorage
from obs import ObsClient


class HuaWeiOss(BaseStorage):

    def setup(self, key_id=None, secret=None, host=None, bucket=None, root_dir='dev', *args, **kwargs):

        host = host.split('://', 1)[-1]
        server = f'https://{host}/'
        self.host = server
        self.obs_client = ObsClient(access_key_id=key_id, secret_access_key=secret, server=server)
        self.root = root_dir.strip('/')
        self.bucket = bucket
        self.bucket_host = f'https://{bucket}.{host}/'

    def object_exists(self, path: str) -> bool:

        """
        20220622 esdk-obs-python v3.22.2sdk
        obsexists
        :param path:
        :return:
        """
        path = self.parse_path(path)
        res = self.obs_client.getObjectMetadata(bucketName=self.bucket, objectKey=path)
        exist = True if res.body else False
        return exist

    def parse_path(self, path):

        if path.startswith('/'):
            return f'{self.root}{path}'
        else:
            return f'{self.root}/{path}'

    async def upload(self, path, data, mode=BaseStorage.Write, expire: int = None):

        """
        @params path:
        @params data:
        @params mode: Write/Append
        @params expire: s
        """
        path = self.parse_path(path)
        if mode == BaseStorage.Append:
            """追加写"""
            self.obs_client.appendObject(bucketName=self.bucket, objectKey=path, content=data)
        else:
            """覆盖写"""
            self.obs_client.putContent(bucketName=self.bucket, objectKey=path, content=data)

    async def download(self, path):

        path = self.parse_path(path)
        result = self.obs_client.getObject(bucketName=self.bucket, objectKey=path)
        return result.body.response.read()

    def download_url(self, file_path):

        return self.host + urllib.parse.quote(self.parse_path(file_path))  #

    async def delete(self, path):
        rel_path = path
        path = self.parse_path(path)
        self.obs_client.deleteObject(bucketName=self.bucket, objectKey=path)

    async def image_resize(self, path, scale):

        scale = int(scale * 100)
        if scale < 1:
            scale = 1
        if scale > 1000:
            scale = 1000
        return f'{path}?x-oss-process=image/resize,p_{scale}', None

    async def get_file_meta(self, path):

        """
        :param path:
        :return: head.last_modified, head.content_type, head.content_length
        head.last_modified: intNone
        head.content_type: MIMENone
        head.content_length(bytes): Content-LengthNone
        """
        path = self.parse_path(path)
        res = self.obs_client.getObjectMetadata(bucketName=self.bucket, objectKey=path)
        head = res.body
        return head.lastModified, head.contentType, head.contentLength

    async def list_dir_files(self, path: str, max_keys=100) -> list:

        """
        max_keys 1-1000 10001000
        pathNone1000
        path/ cemp cemp/
        """
        keys = []
        """
        all_data.body
        {"name": "cemp-tong-dev", "location": "bcs-kfcs-1", "prefix": "cemp/", "max_keys": 1000,
        "is_truncated": false,
        "contents": [{"key": "cemp/test.txt", "lastModified": "2022/06/24 15:24:45", "etag": "\"
        cbcb0b86c691093d0b16d405d5578442\"", "size": 18, "owner": {"owner_id": "3616e223880d4f10b4883cd244fe360d",
        "owner_name": "BCS-KFCS"},
        "storageClass": "STANDARD", "isAppendable": false}], "commonPrefixs": []}
        """
        all_data = self.obs_client.listObjects(bucketName=self.bucket, prefix=path, max_keys=max_keys)
        for obj in all_data.body.contents:
            keys.append(obj.key)
        return keys


# def main():
#     print("oss")
#     config = {"key_id": "Z96ZHSHVCBIICBOO9M1A",
#               "secret": "gkGOsnDcRFg3jSNGcd3oRZDtASYbMUYtgnCe7TP4",
#               "host": "https://100.115.10.252/",
#               "bucket": "cemp-tong-dev",
#               "root_dir": "cemp",
#               "cdn": "http://cdn-source.mis.bcs:8080/se/cemp/"
#               }
#     oss = HuaWeiOss(**config)
    # #
    # try:
    # print("")
    # print(await oss.upload("test.txt", "baby,hello, world!")) # res: {"etag": "\"
    # cbcb0b86c691093d0b16d405d5578442\"", "objectUrl": "https://100.115.10.252/cemp-tong-dev/cemp/test.txt"}
    # except Exception as e:
    # print("")
    # print("e:", e)
    #
    # #
    # try:
    # print("")
    # print(await oss.download("test.txt"))
    # except Exception as e:
    # print("")
    # print("e:", e)
    #
    #
    # try:
    # print("")
    # print(await oss.list_dir_files(path=None))
    # except Exception as e:
    # print("")
    # print("e:", e)
    #
    # #
    # try:
    # print("")
    # print(await oss.get_file_meta("test.txt"))
    # except Exception as e:
    # print("")
    # print("e:", e)
    #
    # #
    # try:
    # print("")
    # print(oss.object_exists("test.txt"))
    # except Exception as e:
    # print("")
    # print("e:", e)
    # #
    # try:
    # print("")
    # print(await oss.delete("test.txt"))
    # except Exception as e:
    # print("")
    # print("e:", e)
